package lingou.homework.postbar.handler;

import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSessionListener;
import lingou.homework.postbar.controller.tool.LogPrinter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Component
public class SessionHandler implements HttpSessionListener {
    @Autowired
    LogPrinter logPrinter;
    private Map<String, HttpSession> map = new HashMap<>();
    public HttpSession getSession(String id) {
        return map.get(id);
    }
    public Collection<HttpSession> getAllSession(){
        return map.values();
    }
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        map.put(se.getSession().getId(), se.getSession());
        HttpSessionListener.super.sessionCreated(se);
        logPrinter.println("Session created:", se.getSession().getId());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        map.remove(se.getSession().getId());
        HttpSessionListener.super.sessionDestroyed(se);
        logPrinter.println("Session destroyed:", se.getSession().getId());
    }
}
